﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.DataSourcesFile;
using System.Runtime.InteropServices;

namespace soufanPrice
{
    public partial class Form1 : Form
    {
        int total = 1;
        int pageIndex = 1;
        IFeatureLayer pIFeatureLayer;
        IWorkspaceEdit pIWorkspaceEdit;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                XmlDocument HousePointXML = getHousePointXML(1);
                pIWorkspaceEdit.StartEditing(true);
                pIWorkspaceEdit.StartEditOperation();
                IFeatureCursor pIFeatureCursor = pIFeatureLayer.FeatureClass.Insert(true);
                //添加第一页坐标信息
                addFeature(HousePointXML, pIFeatureCursor);
                pageIndex++;
                int pagesCount = total / 50 + 1;
                while (pageIndex < pagesCount)
                {
                    HousePointXML = getHousePointXML(pageIndex);
                    //添加后几页坐标信息
                    addFeature(HousePointXML, pIFeatureCursor);
                    pageIndex++;
                    Console.WriteLine(pageIndex.ToString());
                }
                pIFeatureCursor.Flush();
                pIWorkspaceEdit.StopEditOperation();
                pIWorkspaceEdit.StopEditing(true);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pIFeatureCursor);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            pIWorkspaceEdit = initFeatureLayer();
        }
        /// <summary>
        /// 从服务器获取房源地址
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        private XmlDocument getHousePointXML(int pageIndex)
        {
            if (pageIndex <= total)
            {
                HttpWebRequest request = (HttpWebRequest)(WebRequest.Create("http://esf.soufun.com/newsecond/map/interfaces/GetHousePoint.aspx?"));
                string data = "district=&comarea=&trackline=%u660C%u5E73%u7EBF&trackstation=%u6C99%u6CB3%"
                            + "u7AD9&istrack=1&pricemax=&pricemin=&areamax=&areamin=&room=&purpose=%u4F4F%"
                            + "u5B85&orderby=&x1=116.11312866210938&y1=39.68605343225986&x2=116.83135986328125&y2=40"
                            + ".08700262599703&page=" + pageIndex.ToString() + "&schoolprojcodes=&isschool=0&isline=0";
                CookieContainer cookie = new CookieContainer();
                byte[] byteArray = Encoding.UTF8.GetBytes(data);
                request.CookieContainer = cookie;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(byteArray, 0, byteArray.Length);
                stream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                XmlDocument xml = new XmlDocument();
                xml.Load(response.GetResponseStream());
                response.Close();

                XmlNodeList nodes = xml.GetElementsByTagName("allcount");
                if (pageIndex == 1 && nodes != null && nodes.Count > 0)
                {
                    total = int.Parse(nodes[0].InnerText);
                }
                return xml;
            }
            else
            {
                throw new Exception("获取页数操作总页数");
            }
        }
        /// <summary>
        /// 获取房源信息
        /// </summary>
        /// <param name="projID">房源代号</param>
        /// <returns></returns>
        private XmlDocument getHouseDetails(string projID)
        {
            HttpWebRequest request = (HttpWebRequest)(WebRequest.Create("http://esf.soufun.com/newsecond/map/interfaces/getHouseData.aspx?"));
            string data = "purpose=%u4F4F%u5B85&projcodes=" + projID + "&pricemax=&pricemin=&areamax=&areamin=&room=&orderby=&page=1&isbest=0";
            CookieContainer cookie = new CookieContainer();
            byte[] byteArray = Encoding.UTF8.GetBytes(data);
            request.CookieContainer = cookie;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(byteArray, 0, byteArray.Length);
            stream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            XmlDocument xml = new XmlDocument();
            xml.Load(response.GetResponseStream());
            response.Close();
            return xml;
        }

        private IWorkspaceEdit initFeatureLayer()
        {
            IWorkspaceFactory pIWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace pIFeatureWorkspace = pIWorkspaceFactory.OpenFromFile(Application.StartupPath, 0) as IFeatureWorkspace;
            IFeatureClass pIFeatureClass;
            if (File.Exists(Application.StartupPath + @"/Houses.shp"))
            {
                pIFeatureClass = pIFeatureWorkspace.OpenFeatureClass("Houses");
            }
            else
            {
                pIFeatureClass = CreateFeatureClass("Houses", pIFeatureWorkspace, axMapControl1.SpatialReference);
            }
            pIFeatureLayer = new FeatureLayerClass();
            pIFeatureLayer.FeatureClass = pIFeatureClass;
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)pIFeatureWorkspace;
            return workspaceEdit;
        }

        private void addFeature(XmlDocument HousePointXML, IFeatureCursor featureCursor)
        {
            XmlNodeList nodes = HousePointXML.GetElementsByTagName("project");
            foreach (XmlNode node in nodes)
            {
                double x = double.NaN, y = double.NaN;
                string projID = null, projname = null;
                foreach (XmlNode lastChildNode in node.ChildNodes)
                {
                    if (lastChildNode.Name == "px") x = double.Parse(lastChildNode.InnerText);
                    if (lastChildNode.Name == "py") y = double.Parse(lastChildNode.InnerText);
                    if (lastChildNode.Name == "newcode") projID = lastChildNode.InnerText;
                    if (lastChildNode.Name == "projname") projname = lastChildNode.InnerText;
                }
                if (!double.IsNaN(x) && !double.IsNaN(y) && projID != null && projname != null)
                {
                    addFeature(x, y, projname, projID, featureCursor);
                }
            }
        }

        private void addFeature(double x, double y, string name, string projID, IFeatureCursor featureCursor)
        {
            IFeatureBuffer pIFeatureBuffer = pIFeatureLayer.FeatureClass.CreateFeatureBuffer();
            IPoint pIPoint = new PointClass();
            pIPoint.X = x;
            pIPoint.Y = y;
            pIFeatureBuffer.Shape = pIPoint;
            pIFeatureBuffer.set_Value(pIFeatureBuffer.Fields.FindField("Name"), name);
            pIFeatureBuffer.set_Value(pIFeatureBuffer.Fields.FindField("ProjID"), projID);
            featureCursor.InsertFeature(pIFeatureBuffer);
        }

        public IFeatureClass CreateFeatureClass(String featureClassName, IFeatureWorkspace featureWorkspace, ISpatialReference spatialReference)
        {
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;
            IFields fields = ocDescription.RequiredFields;
            int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
            IField field = fields.get_Field(shapeFieldIndex);
            IGeometryDef geometryDef = field.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
            geometryDefEdit.SpatialReference_2 = spatialReference;

            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
            field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = "Name";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldsEdit.AddField(field);
            field = new FieldClass();
            fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = "ProjID";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldsEdit.AddField(field);
            field = new FieldClass();
            fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = "Price";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldsEdit.AddField(field);

            IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, fields,
                ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple,
                fcDescription.ShapeFieldName, "ProjID");
            return featureClass;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int i=0;

            IFeatureCursor pIFeatureCursor = pIFeatureLayer.FeatureClass.Update(null, false);
            IFeature feature = null;
            int priceIndex = pIFeatureCursor.Fields.FindField("Price");
            while ((feature = pIFeatureCursor.NextFeature()) != null)
            {
                i++;
                try
                {
                    if (string.IsNullOrEmpty(feature.get_Value(feature.Fields.FindField("Price")).ToString().Trim()))
                    {
                        XmlDocument xml = getHouseDetails(feature.get_Value(feature.Fields.FindField("ProjID")).ToString());
                        string price;
                        XmlNodeList nodes = xml.GetElementsByTagName("projprice");
                        if (pageIndex == 1 && nodes != null && nodes.Count > 0)
                        {
                            price = nodes[0].InnerText;
                            feature.set_Value(priceIndex, price);
                            pIFeatureCursor.UpdateFeature(feature);
                        }
                    }
                }
                catch
                { }
                Console.WriteLine(i.ToString());
            }
            Marshal.ReleaseComObject(pIFeatureCursor);
        }
    }
}